package org.example.provider.controller;

import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import org.example.provider.domain.Goods;
import org.example.provider.service.GoodsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * @Date: 2024/9/27
 * @Author: Administrator
 * @ClassName: GoodsController
 * @Description: comment here
 */

@RestController
@RequestMapping("/goods")
public class GoodsController {

    @Autowired
    private GoodsService goodsService;

    @Value("${server.port}")
    private String port;
    // 返回一个Goods
    @GetMapping("/{id}")
    @HystrixCommand(fallbackMethod = "getGoods_Fallback")
    public Goods getGoods(@PathVariable("id") Integer id) {
        Goods goods = goodsService.getGoodsById(id);
        goods.setName("goods-" + id + " port:" + port);
        //模拟出异常
        int a=1/0;
        return goods;
    }

    /**
     * 使用Hystrix熔断机制，当服务调用失败时，会自动返回默认值，而不是抛出异常，也就是服务降级
     * 1、方法的返回值要和原方法一致
     * 2、方法前面也和原方法一样加上注解
     */
    public Goods getGoods_Fallback(Integer id) {
        Goods goods = new Goods();
        goods.setGoodsId(-1);
        goods.setName("provider提供方服务降级!");
        goods.setPrice(-999d);
        goods.setStock(-1);
        return goods;
    }

}
